package cn.mymall.web.controller.houtai.user;

import cn.mymall.constant.CachedCont;
import cn.mymall.constant.EMallConstant;
import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.User;
import cn.mymall.service.IUserService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.DateUtil;
import cn.mymall.util.RandomUtil;
import cn.mymall.util.RegexUtil;
import cn.mymall.vo.user.UserResVo;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/user/login")
public class UserLoginController extends BaseHoutaiController {
    @Autowired
    private IUserService userService;

    private final int expireSecond = 300;

    protected String getMobileCodeKey(String mobile) {
        return "houtai_login_" + mobile;
    }

    @RequestMapping("/sendCode")
    public ResultCode sendCode(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return ResultCode.getFailure("手机号格式不正确");
        }
        if (!RegexUtil.isMobile(mobile)) {
            return ResultCode.getFailure("手机格式不正确");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return ResultCode.getFailure("用户不存在");
        }
        String key = getMobileCodeKey(mobile);
        String todayTakeCountKey = CachedCont.getCacheKey("login_send_codecount", DateUtil.format(new Date(), "yyyyMMdd"), mobile);
        Integer getCodeCount = (Integer) redisHelper.get(todayTakeCountKey);
        getCodeCount = getCodeCount == null ? 0 : getCodeCount;
        if (getCodeCount >= 10) {
            return ResultCode.getFailure("当然获取登录验证码次数超限");
        }
        String code = RandomUtil.getDigitalRandomString(6);
        logger.warn("用户{}登录验证码:{},{}", mobile, code, BaseWebUtil.getRemoteIp(getRequest()));
        redisHelper.set(key, code, expireSecond);
        redisHelper.incr(todayTakeCountKey, 1, CachedCont.ONE_DAY);
        return ResultCode.getSuccessReturn(user);
    }

    @RequestMapping("/in")
    public ResultCode<Map> loginIn(String mobile, String code) {
        if (StringUtils.isBlank(mobile)) {
            return ResultCode.getFailure("请输入手机号！");
        }
        if (StringUtils.isBlank(code)) {
            return ResultCode.getFailure("请输入手机验证码！");
        }
        String ckname = getMobileCodeKey(mobile);
        String cacheCode = (String) redisHelper.get(ckname);
        if (StringUtils.isBlank(cacheCode)) {
            return ResultCode.getFailure("验证码不存在或已过期");
        }

        if (!StringUtils.equalsIgnoreCase(code, cacheCode)) {
            logger.warn("验证码错误：{}", mobile);
            String checkCountKey = CachedCont.getCacheKey("check_logincode", DateUtil.getCurDateStr(), mobile);
            Integer checkCount = (Integer) redisHelper.get(checkCountKey);
            checkCount = checkCount == null ? 0 : checkCount;
            if (checkCount >= 10) {
                return ResultCode.getFailure("验证登录验证码次数超限");
            }
            redisHelper.incr(checkCountKey, 1, CachedCont.ONE_HOUR);
            return ResultCode.getFailure("验证码错误");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return ResultCode.getFailure("用户不存在");
        }
        String uuid = "houtai_" + RandomUtil.getRandomString(48);
        redisHelper.set(uuid, user.getId(), CachedCont.ONE_DAY * 5);
        logger.warn("login：{}", mobile);
        Map result = Maps.newHashMap();
        result.put("userId", user.getId());
        result.put("uuid", uuid);
        result.put("username", user.getUsername());
        return ResultCode.getSuccessReturn(result);
    }

    @RequestMapping("/byUUID")
    public ResultCode byAuthcode() {
        HttpServletRequest request = getRequest();
        String auth_code = BaseWebUtil.getHeaderMap(request).get("uuid");
        if (StringUtils.isNotBlank(auth_code)) {
            Integer userId = (Integer) redisHelper.get(auth_code);
            if (userId != null) {
                User user = userService.getById(userId);
                if (StringUtils.equalsIgnoreCase(user.getStatus(), StatusConstant.Y)) {
                    UserResVo userVo = new UserResVo();
                    userVo.setId(user.getId());
                    userVo.setMobile(user.getMobile());
                    userVo.setUsername(user.getUsername());
                    request.setAttribute(EMallConstant.REQUEST_LOGIN_USER, userVo);
                    return ResultCode.SUCCESS;
                }
            }
        }
        return ResultCode.getFailure("未登录");
    }

    @RequestMapping("/out")
    public ResultCode loginOut(String auth_code) {
        redisHelper.delete(auth_code);
        return ResultCode.SUCCESS;
    }
}
